package com.bnz.service.impl;

import com.bnz.mapper.ClassesMapper;
import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.Classes;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service        // 添加service注解
public class StudentServiceImpl implements StudentService {
    @Autowired  // 从spring容器中取得javaBean
    private StudentMapper studentMapper;
    @Autowired
    private ClassesMapper classesMapper;

    // 1. 查询所有学生
    @Override
    public List<Student> findAll() {
        // 1.1 得到学生集合
        List<Student> students = studentMapper.findAll();
        // 1.2 遍历集合，找到每个学生对应的班级
        for (Student student : students) {
            // 1.2.1 根据cid得到对应班级cid
            Integer cid = student.getCid();
            // 1.2.2 从班级集合中找到对应id的班级
            Classes mapper = classesMapper.findById(cid);
            // 1.2.3 得到每个学生对应的班级
            student.setCname(mapper.getCname());
        }
        return students;
    }

    // 2. 分页查询
    @Override
    public PageResult<Student> findByPage(int page, int pageSize) {
        // 2.1 开始分页
        PageHelper.startPage(page,pageSize);
        // 2.2 查询所有学生
        List<Student> students = studentMapper.findAll();
        // 2.3 将学生集合转换为Page<>集合
        Page<Student> studentPage = (Page<Student>) students;
        // 2.4 返回
        return new PageResult<>(studentPage.getTotal(),studentPage.getResult());
    }

    // 3. 条件查询带分页
    @Override
    public PageResult<Student> search(int page, int pageSize, Student student) {
        // 3.1 开始分页
        PageHelper.startPage(page,pageSize);
        // 3.2 根据条件查询学生
        List<Student> students = studentMapper.findByWords(student);
        // 3.3 将学生集合转换为Page<>集合
        Page<Student> studentPage = (Page<Student>) students;
        // 3.4 返回
        return new PageResult<>(studentPage.getTotal(),studentPage.getResult());
    }

    // 4. 添加学生
    @Override
    public void add(Student student) {

    }

}
